#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版自动删除老CSV文件程序
功能：每天0点10分删除指定目录下前天及更早的CSV文件
"""

import os
import glob
from datetime import datetime, timedelta

def delete_old_csv_files(directory_path, file_pattern="*.csv"):
    """
    删除指定目录下前天及更早的CSV文件
    
    Args:
        directory_path (str): 目标目录路径
        file_pattern (str): 文件匹配模式，默认为*.csv
    """
    
    print(f"=== 开始检查目录: {directory_path} ===")
    print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    if not os.path.exists(directory_path):
        print(f"错误: 目录不存在 - {directory_path}")
        return
    
    # 获取截止日期（前天0点）
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    cutoff_date = today - timedelta(days=2)
    print(f"删除截止日期: {cutoff_date.strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    # 查找所有CSV文件
    search_pattern = os.path.join(directory_path, file_pattern)
    files = glob.glob(search_pattern)
    
    if not files:
        print("未找到CSV文件")
        return
    
    print(f"找到 {len(files)} 个CSV文件")
    print()
    
    # 分析和处理文件
    files_to_delete = []
    files_to_keep = []
    
    for file_path in files:
        filename = os.path.basename(file_path)
        
        # 尝试从文件名解析日期（格式：YYYYMMDDHHMMSS.csv）
        try:
            if filename.endswith('.csv') and len(filename) >= 19:
                # 提取日期时间部分
                date_part = filename[:14]  # YYYYMMDDHHMMSS
                year = int(date_part[:4])
                month = int(date_part[4:6])
                day = int(date_part[6:8])
                file_date = datetime(year, month, day, 0, 0, 0)
                
                # 判断是否需要删除
                if file_date < cutoff_date:
                    files_to_delete.append((file_path, file_date, filename))
                else:
                    files_to_keep.append((file_path, file_date, filename))
                    
        except (ValueError, IndexError):
            print(f"警告: 无法解析文件日期 - {filename}")
            continue
    
    # 显示结果
    print(f"保留文件: {len(files_to_keep)} 个")
    for _, file_date, filename in files_to_keep:
        print(f"  ✓ {filename} ({file_date.strftime('%Y-%m-%d')})")
    print()
    
    if files_to_delete:
        print(f"准备删除: {len(files_to_delete)} 个文件")
        total_size = 0
        
        for file_path, file_date, filename in files_to_delete:
            file_size = os.path.getsize(file_path)
            total_size += file_size
            print(f"  🗑️  {filename} ({file_date.strftime('%Y-%m-%d')}) - {file_size:,} bytes")
        
        print(f"\n将释放空间: {total_size:,} bytes ({total_size/1024:.1f} KB)")
        print()
        
        # 执行删除
        deleted_count = 0
        for file_path, file_date, filename in files_to_delete:
            try:
                os.remove(file_path)
                print(f"✓ 已删除: {filename}")
                deleted_count += 1
            except OSError as e:
                print(f"✗ 删除失败: {filename} - {e}")
        
        print(f"\n删除完成: 成功删除 {deleted_count} 个文件")
    else:
        print("没有需要删除的文件")
    
    print("=" * 50)

if __name__ == "__main__":
    # 配置参数
    target_dir = r"D:\works\water\data\file\local\1\1\1\5"  # 修改为你的实际目录
    
    # 执行删除操作
    delete_old_csv_files(target_dir)
    
    # 等待用户按回车键退出
    input("\n按回车键退出...")